package com.example.administrator.a14_1locationmanager431;

import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
implements LocationListener{

    static final int MIN_TIME = 5000; // 位置更新条件:5000 毫秒(=5 秒)
    static final int MIN_DIST = 1;   // 位置更新条件:5米
    LocationManager mgr; // 定位管理器
    TextView txv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txv = (TextView) findViewById(R.id.txv);
        mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
    }

    protected void onResume(){
        super.onResume();

        String best = mgr.getBestProvider(new Criteria(),true); // 找出已启用的提供者
        if(best != null){ // 如果有定位提供者可用
            txv.setText("获取定位信息中...");
            mgr.requestLocationUpdates(best, MIN_TIME, MIN_DIST, this); //注册位置事件监听器
        }else{
            txv.setText("请确认已开启定位功能!");
        }
    }
    @Override
    protected void onPause(){
        super.onPause();
        mgr.removeUpdates(this); // 取消注册更新事件
    }
    @Override
    public void  onLocationChanged(Location location){ //位置变更事件
        txv.setText("123");
        String str = "定位提供者:"+location.getProvider();
        str+=String.format("\n纬度:%.5f\n 经度:%.5f\n高度:%.2f米",
                location.getLatitude(),
                location.getLongitude(),
                location.getAltitude());
        txv.setText(str);
    }
    @Override
    public void onProviderDisabled(String provider){}
    @Override
    public void onProviderEnabled(String provider){}
    @Override
    public void onStatusChanged(String provider, int status,Bundle extras){}

    public void setup(View v){
        Intent it = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(it);
    }

}
